// 权限控制
// 1.路由跳转权限控制
// 2.菜单权限控制

import router from '@/router'
import store from '@/store'
import { getToken } from './utils/auth'
const WHITELIST = ['/login', '/404']
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router/asyncRoutes'
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    // 有token
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 这个位置是
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/fetchUserInfo')
        console.log('action内部传出的数据', res)
        // 拿到给好的权限
        const menus = res.roles.menus
        console.log(menus)
        // 把有的权限的路由返回
        const filterRoutes = asyncRoutes.filter(route => menus.includes(route.children[0].name))
        // 把路由放到
        router.addRoutes(filterRoutes)
        store.commit('menu/setMenuList', filterRoutes)
        console.log(filterRoutes)
      }
    }
  } else {
    // 没有token
    if (WHITELIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})
